/*
 * This servlet runs once every 48 hours automatically by the server. 
 * It deleted unactivated members.
 */
package controllers.classes;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import classes.HibernateUtil;
import dao.ActivationDao;
import models.Activation;
import dao.StudentDao;
import models.User;
import dao.UserDao;

@WebListener
public class BackgroundJobManagerController implements ServletContextListener {

    private ScheduledExecutorService scheduler;
    private Runnable run = new Runnable() {
        public void run() {
            HibernateUtil hu = new HibernateUtil();
            ActivationDao ad = new ActivationDao(hu.openSession());
            UserDao ud = new UserDao(hu.openSession());

            StudentDao sd = new StudentDao(hu.openSession());
            /*
             * Select the members (objects) who are not activated yet
             * Delete the unactivated members object
             * Delete the student object
             * Delete the member object as last (to prevent child/parent error)
             */

            for (User usr : ud.findAllUnactivatedUsers()) { //For each user in the list of not activated users as usr, perform cleanup
                //Delete activation object
                Activation temp_act = ad.findByStudentId(usr.getMember_id());
                ad.delete(temp_act);

                //Delete student object
                sd.delete(sd.get(usr.getMember_id()));

                //Delete member object
                ud.delete(usr);
            }
            
            hu.close(); //close connection
        }
    };

    @Override
    public void contextInitialized(ServletContextEvent event) {
        scheduler = Executors.newSingleThreadScheduledExecutor();
        scheduler.scheduleAtFixedRate(run, 0, 2, TimeUnit.DAYS);

    }

    @Override
    public void contextDestroyed(ServletContextEvent event) {
        scheduler.shutdownNow();
    }
}